<script lang="ts" setup>
import { getUserInformation, imgUpload, setUserInfo } from '@/api/user';
import ChangeEmail from '@/components/user/ChangeEmail.vue';
import ChangePhoneNumber from '@/components/user/ChangePhoneNumber.vue';
import { useUserStore } from '@/stores/user';
import { useUserProfileStore } from '@/stores/userProfile';
import { ElMessage } from 'element-plus';
import { computed, onMounted, reactive } from 'vue';

const data_rate = reactive<number[]>([1,1,2,2,3,3,4,4])

//获取用户信息
const userStore =  useUserStore()

const {userInfor} = useUserProfileStore()

const userInformationData = async() => {
  const {data} = await getUserInformation(userStore.userId)
  Object.assign(userInfor,data.data)
  console.log(userInfor)
}

onMounted(() => {
  userInformationData()
})

//资料完成度
const dataRateCom = computed(() => {
  const rate = <number[]>[0]
  if (userInfor.name != '') rate.push(1)
  if (userInfor.avatarUrl != '') rate.push(2)
  if (userInfor.email != '') rate.push(3)
  if (userInfor.phoneNumber != '') rate.push(4)
  return rate
})

// 计算非空值占比并保留1位小数
const nonEmptyRatio = computed(() => {
  const totalKeys = Object.keys(userInfor).length;
  if (totalKeys === 0) return 0;

  const nonEmptyCount = Object.values(userInfor).filter(value => value != null && value !== '').length;

  // 计算非空值比例并返回数字类型
  return parseFloat(((nonEmptyCount / totalKeys) * 100).toFixed(1));
});

// 脸部logo
const faceCom = computed(() => {
  if (nonEmptyRatio.value <= 40) {
    return '/src/assets/face/cry.png';
  } else if (nonEmptyRatio.value <= 80) {
    return '/src/assets/face/wawa.png';
  } else {
    return '/src/assets/face/smile.png';
  }
});


// 处理上传文件
const imgUploadData = async(img:File) => {
  const formData = new FormData();
  formData.append('file', img);
  const {data} = await imgUpload(formData)
  userInfor.avatarUrl = data.data
}

const handleFileChange = (event: Event) => {
  const target = event.target as HTMLInputElement;
  console.log(target.files)
  if (target.files && target.files.length > 0) {
    // 更新 avatar_file 引用为用户选择的第一个文件
    imgUploadData(target.files[0])

  }
}


//保存
const setUserInformation = async() => {
  if(userInfor.name === ''){
    ElMessage.error("用户名不能为空")
    return
  }
  const {data} = await setUserInfo(userInfor)
  if(data.code === 1) {
    Object.assign(userStore.userInfo,userInfor)
    ElMessage.success("保存成功")
    return
  }
  ElMessage.error(data.msg)

}


//邮箱展示
function maskEmail(email: string): string {
  if (!email) return '';

  const emailParts = email.split('@');
  if (emailParts.length !== 2) return email;

  const userPart = emailParts[0];
  const domainPart = emailParts[1];

  // 对于用户部分，保留首尾字符，其余用 * 代替
  const maskedUser = userPart.length > 2 ? `${userPart[0]}${'*'.repeat(userPart.length - 2)}${userPart[userPart.length - 1]}` : '*'.repeat(userPart.length);

  return `${maskedUser}@${domainPart}`;
}
const emailCom = computed(() => {
  return maskEmail(userInfor.email)
})

//手机号展示
function maskPhoneNumber(phoneNumber: string): string {
  if (!phoneNumber || phoneNumber.length < 7) return phoneNumber;

  // 假设手机号为11位，如中国的手机号格式
  const visibleStart = 3;
  const visibleEnd = 4;
  const maskLength = phoneNumber.length - visibleStart - visibleEnd;

  return `${phoneNumber.substring(0, visibleStart)}${'*'.repeat(maskLength)}${phoneNumber.substring(phoneNumber.length - visibleEnd)}`;
}
const phoneCom = computed(() => {
  return maskPhoneNumber(userInfor.phoneNumber)
})

//表单控制
const userProfileStore = useUserProfileStore()

//邮箱按钮字体显示
const emailButtonTextCom = computed(() => {
  return userInfor.email==='' ? "绑定邮箱" : "更换邮箱"
})

</script>
<template>
  <ChangePhoneNumber/>
  <ChangeEmail />

  <div class="main">
    <div class="basic-information-span">
      <span>基本信息</span>
      <el-avatar :src="userInfor.avatarUrl"/>
      <input type="file" id="file-upload" @change="handleFileChange" accept="image/*" style="display: none;" />
          <!-- 标签关联到文件输入框 -->
      <label for="file-upload" id="upload-label">修改头像</label>
    </div>
    <div class="completion">
      <div class="head">
        您的资料完成度：
        <span>{{ nonEmptyRatio }} %</span>
      </div>

      <div class="footer_1">/
        <div class="footer">
          <div class="data-rate"
         v-for="item in data_rate" :key="item"
         :class="{ 'active': item in dataRateCom}"
         >
          </div>
        </div>
        <el-avatar :src="faceCom"/>
      </div>
    </div>

    <div class="information-main">
      <div class="userInformation">
        <div class="input">
          <span>用户名*</span>
          <input type="text" class="custom-input" placeholder="输入您的用户名" v-model="userInfor.name">
        </div>

        <div class="input">
          <span>邮箱*</span>
          <span class="rightInfor">{{ emailCom }}</span>
          <el-button @click="userProfileStore.isEmail = true" >{{ emailButtonTextCom }}</el-button>
        </div>
      </div>

      <div class="userInformation">

        <div class="input">
          <span>创建时间*</span>
          <span class="rightInfor">{{ userInfor.createdAt }}</span>
        </div>


        <div class="input">
          <span>手机号*</span>
          <span class="rightInfor">{{ phoneCom }}</span>
          <el-button @click="userProfileStore.isPhone=true">更换手机号</el-button>
        </div>
      </div>

      <div class="save">
            <el-button @click="setUserInformation">保存</el-button>
      </div>
    </div>
    <hr/>
  </div>
</template>


<style lang="scss" scoped>
.main{
  .basic-information-span{
    display: flex;
    gap:20px;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    span:first-child{
      color:white;
      font-size: 30px;
    }
    .el-avatar{
      height: 100px;
      width: 100px;
      background: no-repeat center / 40px auto;
    }
    #file-upload {
            display: none; /* 或者使用 visibility: hidden; */
        }

    /* 可选：为 label 添加样式 */
    #upload-label {
        cursor: pointer;
        color: rgb(218, 218, 218);
        text-decoration: none;
    }
  }

  .completion{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .head{
      color:white;
      padding-left: 10px;
      margin-top: 20px;
      span{
        color:#129eff
      }
    }
    .footer_1{
      display: flex;
      .el-avatar{
        margin-top: 7px;
        background-color: black;
      }
    }
    .footer{
      display: flex;
      gap: 10px;
      .data-rate{
        margin-top: 20px;
        width: 100px;
        height: 20px;
        background-color: white;
      }
      .data-rate:first-child{
        border-top-left-radius: 10px;
        border-bottom-left-radius: 10px;
      }
      .data-rate:last-child{
        border-top-right-radius: 10px;
        border-bottom-right-radius: 10px;
      }
      .data-rate.active{
        background: linear-gradient(90deg, #aaf7ff, #e5c1ff);
      }
    }
  }
  .userInformation{
    margin: 0 15%;
    margin-top: 5%;
    color: white;
    display: flex;
    justify-content: space-between;
    .input{
      // height: 50px;
      gap:10px;
      display: flex;
      align-items: center;
      .custom-input {
            // width: 100%;
            padding: 5px;
            color:white;
            border-top: none;
            border-right: none;
            border-left: none;
            border-bottom: 1px solid #ccc;
            outline: none; /* 移除焦点时的轮廓 */
            background-color: transparent;
            font-size: 16px;
      }

      .rightInfor{
        font-size: 18px;
      }
    }
  }

  .save{
    display: flex;
    margin-top: 5%;
    justify-content: center;
    margin-bottom: 5%;
  }
}
</style>
